<template>
  <view class="page">
    <!-- 页头导航 -->
    <view class="header-nav">
      <view class="nav-left" @tap="goBack">
        <image
          class="back-icon"
          src="/static/icons/left_arrow.png"
          mode="aspectFit"
        ></image>
      </view>
      <view class="nav-title">创建公司</view>
      <view class="nav-right"></view>
    </view>

    <!-- 内容区域 -->
    <view class="container">
      <!-- 提示信息 -->
      <view class="notice-section">
        <text class="notice-text"
          >新创建的公司将会进行信息审核，请确保填入的信息真实有效</text
        >
      </view>

      <!-- 表单区域 -->
      <view class="form-section">
        <!-- 公司名称 -->
        <view class="form-item">
          <view class="form-label">公司名称</view>
          <view v-if="formData.companyName && companyName" class="form-value fixed">{{ formData.companyName }}</view>
          <input
            v-else
            class="form-input"
            v-model="formData.companyName"
            placeholder="请输入公司名称（2-50个字符）"
            maxlength="50"
          />
        </view>

        <!-- 公司简称 -->
        <view class="form-item">
          <view class="form-label">公司简称</view>
          <input
            class="form-input"
            v-model="formData.shortName"
            placeholder="请输入公司简称（2-20个字符）"
            maxlength="20"
          />
        </view>

        <!-- LOGO -->
        <view class="form-item">
          <view class="form-label">LOGO</view>
          <view class="upload-section" @tap="chooseLogo">
            <image
              v-if="formData.logo"
              :src="formData.logo"
              class="upload-image"
              mode="aspectFit"
            ></image>
            <view v-else class="upload-placeholder">
              <text class="upload-text">点击上传LOGO</text>
            </view>
          </view>
        </view>

        <!-- 公司行业 -->
        <view class="form-item">
          <view class="form-label">公司行业</view>
          <view
            class="picker-value"
            @tap="showIndustryPicker = true"
            :class="{ disabled: topIndustryList.length === 0 }"
          >
            {{ selectedIndustryName || "请选择行业" }}
            <text class="arrow">></text>
          </view>
        </view>

        <!-- 行业选择弹窗 -->
        <view v-if="showIndustryPicker" class="industry-modal">
          <view class="modal-mask" @tap="showIndustryPicker = false"></view>
          <view class="industry-picker-popup">
            <view class="popup-header">
              <text class="popup-title">选择行业</text>
              <text class="popup-close" @tap="showIndustryPicker = false"
                >×</text
              >
            </view>
            <scroll-view class="industry-list" scroll-y>
              <view
                v-for="item in topIndustryList"
                :key="item.id"
                class="industry-item"
              >
                <view class="top-industry">
                  <text class="industry-name" style="color: #666">{{
                    item.name
                  }}</text>
                  <view class="industry-actions">
                    <text
                      v-if="!item.loaded || item.children.length > 0"
                      class="expand-icon"
                      @tap="toggleIndustry(item)"
                      >{{ item.expanded ? "▼" : "▶" }}</text
                    >
                  </view>
                </view>

                <view v-if="item.expanded" class="second-industry-list">
                  <view
                    v-for="child in item.children"
                    :key="child.id"
                    class="second-industry"
                    :class="{ selected: child.selected }"
                    @tap="selectIndustry(child)"
                  >
                    <text class="industry-name">{{ child.name }}</text>
                  </view>

                  <view
                    v-if="item.loaded && item.children.length === 0"
                    class="no-data"
                  >
                    暂无二级行业
                  </view>
                </view>
              </view>
            </scroll-view>
          </view>
        </view>

        <!-- 人员规模 -->
        <view class="form-item">
          <view class="form-label">人员规模</view>
          <picker
            mode="selector"
            :range="staffSizeList"
            :value="
              formData.peopleSize
                ? staffSizeList.findIndex(
                    (item) => item.value === formData.peopleSize
                  )
                : -1
            "
            range-key="value"
            @change="onStaffSizeChange"
          >
            <view class="picker-value">
              <text class="picker-text">{{ formData.peopleSize || "请选择人员规模" }}</text>
              <text class="arrow">></text>
            </view>
          </picker>
        </view>

        <!-- 营业执照 -->
        <view class="form-item">
          <view class="form-label">营业执照</view>
          <view class="upload-section" @tap="chooseLicense">
            <image
              v-if="formData.bizLicense"
              :src="formData.bizLicense"
              class="upload-image"
              mode="aspectFit"
            ></image>
            <view v-else class="upload-placeholder">
              <text class="upload-text">点击上传营业执照</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 提交按钮 -->
      <view class="submit-section">
        <button class="submit-btn" @tap="submitForm" :disabled="!canSubmit">
          提交审核
        </button>
        <text class="submit-tip">审核结果将在我的消息-系统通知中展示，请您留意</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { chooseFile, uploadFile2OSS } from "@/utils/file.js";
import {
  getApplyUploadSignApi,
  submitCompanyApplyApi,
  getIndustryTopListApi,
  getChildrenIndustryApi,
  getStaffSizeDataApi,
} from "@/api/company.js";

// 获取路由参数
const companyName = ref("");

onLoad((options) => {
  if (options && options.companyName) {
    const decodedName = decodeURIComponent(options.companyName);
    companyName.value = decodedName;
    formData.value.companyName = decodedName;
  }

  // 加载数据
  loadIndustryData();
  loadStaffSizeData();
});

// 表单数据
const formData = ref({
  id: "", // 企业ID，重新审核时需要传
  companyName: "", // 企业名称
  shortName: "", // 企业短名
  logo: "", // 企业logo
  bizLicense: "", // 营业执照
  industry: "", // 所在行业
  peopleSize: "", // 人员规模/企业规模
});

// 行业数据
const topIndustryList = ref([]);
const industryCache = ref({}); // 缓存二级行业数据

// 人员规模数据
const staffSizeList = ref([]);

// 选择状态
const selectedIndustryName = ref("");
const showIndustryPicker = ref(false);

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 加载一级行业数据
const loadIndustryData = async () => {
  try {
    uni.showLoading({ title: "加载中..." });
    const data = await getIndustryTopListApi();
    topIndustryList.value = (data || [])
      .sort((a, b) => (a.sort || 0) - (b.sort || 0))
      .map((item) => ({
        ...item,
        children: [],
        expanded: false,
        loaded: false,
      }));
    uni.hideLoading();
  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: "加载行业数据失败",
      icon: "none",
    });
  }
};

// 加载二级行业数据
const loadSecondIndustry = async (parentItem) => {
  const topIndustryId = parentItem.id;
  // 检查缓存
  if (industryCache.value[topIndustryId]) {
    parentItem.children = industryCache.value[topIndustryId];
    parentItem.loaded = true;
    return;
  }

  try {
    uni.showLoading({ title: "加载中..." });
    const data = await getChildrenIndustryApi(topIndustryId);
    const secondList = (data || []).sort(
      (a, b) => (a.sort || 0) - (b.sort || 0)
    );
    parentItem.children = secondList;
    parentItem.loaded = true;
    industryCache.value[topIndustryId] = secondList;
    uni.hideLoading();
  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: "加载二级行业失败",
      icon: "none",
    });
  }
};

// 加载人员规模数据
const loadStaffSizeData = async () => {
  try {
    const data = await getStaffSizeDataApi();
    staffSizeList.value = (data || []).sort(
      (a, b) => (a.sort || 0) - (b.sort || 0)
    );
  } catch (error) {
    uni.showToast({
      title: "加载人员规模数据失败",
      icon: "none",
    });
  }
};

// 选择LOGO
const chooseLogo = async () => {
  try {
    const tempFilePath = await chooseFile({
      count: 1,
      mediaType: ["image"],
      sourceType: ["album", "camera"],
    });
    
    if (!tempFilePath) return;

    uni.showLoading({ title: "上传中..." });
    const uploadUrl = await uploadFile2OSS(
      tempFilePath,
      "company",
      getApplyUploadSignApi
    );
    formData.value.logo = uploadUrl;
    uni.hideLoading();
  } catch (error) {
    console.log(error);
    
    uni.hideLoading();
    uni.showToast({
      title: "上传失败，请重试",
      icon: "none",
    });
  }
};

// 选择营业执照
const chooseLicense = async () => {
  try {
    const tempFilePath = await chooseFile({
      count: 1,
      mediaType: ["image"],
      sourceType: ["album", "camera"],
    });
    
    if (!tempFilePath) return;

    uni.showLoading({ title: "上传中..." });
    const uploadUrl = await uploadFile2OSS(
      tempFilePath,
      "company",
      getApplyUploadSignApi
    );
    formData.value.bizLicense = uploadUrl;
    uni.hideLoading();
  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: "上传失败，请重试",
      icon: "none",
    });
  }
};

// 事件处理函数
const toggleIndustry = async (item) => {
  item.expanded = !item.expanded;

  if (item.expanded && !item.loaded) {
    await loadSecondIndustry(item);
  }
};

const selectIndustry = (industry) => {
  formData.value.industry = industry.name;
  selectedIndustryName.value = industry.name;
  showIndustryPicker.value = false;

  // 重置所有选中状态
  topIndustryList.value.forEach((item) => {
    if (item.children) {
      item.children.forEach((child) => (child.selected = false));
    }
  });

  industry.selected = true;
};

// 人员规模选择
const onStaffSizeChange = (e) => {
  const index = parseInt(e.detail.value);
  if (index >= 0 && staffSizeList.value[index]) {
    const staffSize = staffSizeList.value[index];
    formData.value.peopleSize = staffSize.value;
  } else {
    formData.value.peopleSize = "";
  }
};

// 是否可以提交
const canSubmit = computed(() => {
  // 如果有传入的公司名称参数，则不需要验证公司名称
  const hasCompanyNameParam = companyName.value && companyName.value.trim() !== '';
  
  const requiredFields = [
    formData.value.shortName,
    formData.value.industry,
    formData.value.peopleSize,
    formData.value.bizLicense,
    formData.value.logo
  ];
  
  // 如果没有传入公司名称参数，则公司名称也是必填的
  if (!hasCompanyNameParam) {
    requiredFields.push(formData.value.companyName);
  }
  
  return requiredFields.every(field => field && field.trim() !== '');
});

// 提交表单
const submitForm = async () => {
  if (!canSubmit.value) return;

  try {
    uni.showLoading({
      title: "提交中...",
      mask: true,
    });

    // 准备提交数据
    const submitData = {
      id: formData.value.id,
      companyName: formData.value.companyName,
      shortName: formData.value.shortName,
      logo: formData.value.logo,
      bizLicense: formData.value.bizLicense,
      industry: formData.value.industry,
      peopleSize: formData.value.peopleSize,
    };

    // 如果没有传入公司名称参数，确保公司名称不为空
    if (!companyName.value && (!submitData.companyName || submitData.companyName.trim() === '')) {
      uni.showToast({
        title: '请输入公司名称',
        icon: 'none',
      });
      return;
    }

    // 调用提交审核接口
    await submitCompanyApplyApi(submitData);

    uni.hideLoading();
    uni.showToast({
      title: "提交成功",
      icon: "success",
    });

    // 延迟返回
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: error.message,
      icon: "none",
    });
  }
};
</script>

<style scoped>
.page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header-nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 30rpx 20rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.nav-left {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 40rpx;
  height: 40rpx;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.nav-right {
  width: 60rpx;
  height: 60rpx;
}

.container {
  padding: 20rpx;
}

.notice-section {
  background-color: #fffbe6;
  border: 1rpx solid #ffe58f;
  border-radius: 8rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.notice-text {
  font-size: 28rpx;
  color: #faad14;
  line-height: 1.5;
}

.form-section {
  background-color: #fff;
  border-radius: 8rpx;
  overflow: hidden;
}

.form-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.form-item:last-child {
  border-bottom: none;
}

.form-label {
  width: 180rpx;
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}

.form-input {
  flex: 1;
  font-size: 32rpx;
  color: #333;
  border: none;
  outline: none;
}

.form-value {
  flex: 1;
  font-size: 32rpx;
  color: #333;
}

.form-value.fixed {
  color: #999;
}

.picker-value {
  flex: 1;
  font-size: 32rpx;
  color: #333;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.picker-text {
  flex: 1;
  margin-right: 40rpx;
}

.picker-value .arrow {
  color: #999;
  font-size: 28rpx;
  flex-shrink: 0;
}

.picker-value.disabled {
  color: #999;
}

/* 行业选择弹窗样式 */
.industry-picker-popup {
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;
  max-height: 80vh;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.popup-close {
  font-size: 40rpx;
  color: #999;
  padding: 0 20rpx;
}

.industry-list {
  max-height: 70vh;
}

.industry-item {
  border-bottom: 1rpx solid #f5f5f5;
}

.top-industry {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background: #fafafa;
}

.industry-name.selected {
  color: #007aff;
  font-weight: bold;
}

.industry-name {
  font-size: 30rpx;
  color: #333;
  flex: 1;
}

.top-industry .industry-name {
  color: #666;
  font-weight: bold;
}

.industry-actions {
  margin-left: 20rpx;
}

.expand-icon {
  color: #999;
  font-size: 24rpx;
}

.second-industry-list {
  background: #fff;
}

.second-industry {
  padding: 25rpx 30rpx 25rpx 60rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.second-industry:last-child {
  border-bottom: none;
}

.second-industry.selected {
  background: #e6f7ff;
}

.second-industry .industry-name {
  font-size: 28rpx;
  color: #666;
}

.no-data {
  padding: 30rpx 60rpx;
  text-align: center;
  color: #999;
  font-size: 28rpx;
}

/* 行业选择弹窗遮罩 */
.industry-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 999;
}

.modal-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
}

.industry-picker-popup {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;
  max-height: 80vh;
  animation: slideUp 0.3s ease-out;
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

.arrow {
  color: #999;
  font-size: 28rpx;
}

.upload-section {
  flex: 1;
  min-height: 120rpx;
  border: 2rpx dashed #ddd;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
}

.upload-image {
  width: 100%;
  height: 120rpx;
  object-fit: contain;
}

.upload-placeholder {
  text-align: center;
  color: #999;
}

.upload-text {
  font-size: 28rpx;
}

.submit-section {
  margin-top: 40rpx;
  padding: 0 20rpx;
}

.submit-btn {
  width: 100%;
  height: 88rpx;
  background-color: #007aff;
  color: #fff;
  font-size: 32rpx;
  border: none;
  border-radius: 44rpx;
}

.submit-btn[disabled] {
  background-color: #c0c0c0;
  color: #fff;
}
</style>